package top.shiyiri.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/2/9 14:20
 */
public class SessionServlet extends BaseServlet {

    /**
     * 创建Session对象
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建和获取session会话对象
        HttpSession session = request.getSession();
        //判断当前Session会话，是否是新创建出来的
        boolean isNew = session.isNew();
        //获取Session会话的唯一标识 id
        String id = session.getId();
        response.getWriter().write("得到的Session，它的id是：" + id + "<br/>");
        response.getWriter().write("整个Session是否是新创建的：" + isNew);
    }

    /**
     * 往Session中保存数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("key1", "value1");
    }

    /**
     * 获取Session域中的数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object key1 = request.getSession().getAttribute("key1");
        System.out.println(key1);
        response.getWriter().write("从Session中获取出key1的数据是：" + key1);
    }

    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取了Session的默认超时时长
        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
        response.getWriter().write("Session的默认超时时长为：" + maxInactiveInterval + " 秒");
    }

    protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //先获取Session对象
        HttpSession session = request.getSession();
        //设置当前Session 3 秒后超时
        session.setMaxInactiveInterval(3);
        response.getWriter().write("当前Session已经设置为三秒后超时");
    }

    protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //先获取Session对象
        HttpSession session = request.getSession();
        //让Session会话马上超时
        session.invalidate();
        response.getWriter().write("Session已经超时");
    }

    protected void dd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
